package com.staplehurst.pull.refresh;

import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.staplehurst.pull.refresh.PullableList;
import com.staplehurst.pull.refresh.R;
import com.staplehurst.pull.refresh.PullableList.PullUpdateListener;

public class PullToRefreshActivity extends Activity implements Runnable {

	private String[] mListItems = {"Sean", "Marc", "Peta", "Stewart", "Yvonne", "Ronnie",
			"Ruby", "Ian", "Simon", "Paul"};
	private PullableList mPullList;
	private static final String TAG = "PullToRefreshActivity";
	private ArrayAdapter<String> mAdapter;
	private Thread mThread;
	private static final int LIST_SORTED = 1;
	private static final int THREAD_ERROR = 2;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , mListItems);

		/*
		 * Possibly use constructor for header colors, work in progress...
		 * 
		 * mPullList = new PullableList(this, Color.BLACK, Color.RED, Color.RED, Color.RED);
		 * 
		 * mPullList.setHeaderBackgroundColor(Color.BLACK);
		 * mPullList.setHeaderArrowColor(Color.RED);
		 * mPullList.setHeaderRefreshTextColor(Color.RED);
		 * mPullList.setHeaderRefreshTimeColor(Color.RED);
		 * 
		 */

		mPullList = new PullableList(this);
		mPullList = (PullableList)findViewById(R.id.list);
		mPullList.setHeader(this);
		mPullList.setAdapter(mAdapter);       

		mPullList.setPullUpdateListener(new PullUpdateListener() {

			@Override
			public void onUpdateList() {
				// TODO Auto-generated method stub				
				mThread = new Thread(PullToRefreshActivity.this);
				mThread.start();                
			}

		});
	}

	public void run() {
		Message msg;
		msg = Message.obtain();	
		try {

			/*
			 * This is just an example to sort the list of names with a delay
			 * of 3 seconds.
			 */

			Thread.sleep(3000);
			Arrays.sort(mListItems);
			msg.what = LIST_SORTED;
		} catch (InterruptedException e) {
			e.printStackTrace();
			msg.what = THREAD_ERROR;
		}		
		handler.sendMessage(msg);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch(msg.what) {        	
			case LIST_SORTED:
				mAdapter.notifyDataSetChanged();
				mPullList.updateComplete();
				break;

			}
			super.handleMessage(msg);

		}
	};
}